<?php

namespace common\behavior\CommonMessagePushing;


use common\model\EntityModel;
use common\model\ProjectMemberModel;
use common\model\TaskModel;
use common\model\UserModel;
use common\service\BehaviorService;
use common\service\EntityService;
use common\service\OptionsService;
use common\service\ProjectService;
use common\service\TaskService;
use common\service\UserService;
use Webman\Stomp\Client;

/**
 * 实体废除启用事件 推送消息到队列 异步发送小助手消息
 */
class EntityDeprecateBehavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        /***********  预处理开始  ************/
        $params = BehaviorService::getInstance()->dealParam(
            $params,
            [
                'entity_id' => 'intval',
                'operate' => 'strval',
                'operate_at' => 'intval',
                'operator' => 'intval',
            ],
            [
                'entity_id' => 0,
                'operate' => '',
                'operate_at' => 0,
                'operator' => 0,
            ],
            'data',
            ['type' => 'entity_deprecated'],
        );
        /***********  行为判断  ************/
        if ($params === false) {
            return;
        }
        /***********  变量迁移  ************/
        list($entityId, $operate, $operate_at, $operator) = $params;
        if (empty($entityId) || empty($operate)) {
            return;
        }
        /***********  预处理结束  ************/

        /***********  原逻辑迁移  ************/
        $enable = $operate === 'Ena';
        $entity = model(EntityModel::class)->find($entityId);
        if (empty($entity)) {
            return;
        }
        $entityScoped = EntityService::getInstance()->getEntityScoped($entity);
        if (empty($entityScoped)) {
            return;
        }

        $queryFields = [
            'task.id',
            'task.name',
            'task.executor',
            'task.tenant_id',
            'task.project_id',
            'task.assignee_producer',
            'task.department_id',
            'task.entity_module_id',
            'task.step_category_id',

            'entity.id',
            'entity.name',
            'entity.initial_episode_code',
            'entity.showings_number',
        ];
        $relatePeopleTasks = model(TaskModel::class)
            ->join('entity on entity.id = task.entity_id')
            ->where(['entity.id' => ['IN', array_column($entityScoped, 'id')]])
            ->field(build_complex_query_fields($queryFields, '__'))
            ->select();
        if (empty($relatePeopleTasks)) {
            return;
        }
        // 抽取数据
        $userIdList = [];
        $projectIdList = [];
        $departmentIdList = [];
        $tenantIdList = [];

        $projectTaskStepCategoryList = [];
        foreach ($relatePeopleTasks as &$relatePeopleTask) {
            $relatePeopleTask = separate_complex_query_data($relatePeopleTask, '__');
            if (!in_array($relatePeopleTask['task']['step_category_id'] ?? 0, $projectTaskStepCategoryList[$relatePeopleTask['task']['project_id']] ?? [])) {
                $projectTaskStepCategoryList[$relatePeopleTask['task']['project_id']][] = $relatePeopleTask['task']['step_category_id'];
            }
            $userIdList[$relatePeopleTask['task']['executor']] = $relatePeopleTask['task']['executor'];
            $userIdList[$relatePeopleTask['task']['assignee_producer']] = $relatePeopleTask['task']['assignee_producer'];
            $projectIdList[$relatePeopleTask['task']['project_id']] = $relatePeopleTask['task']['project_id'];
            $departmentIdList[$relatePeopleTask['task']['department_id']] = $relatePeopleTask['task']['department_id'];
            $tenantIdList[$relatePeopleTask['task']['tenant_id']] = $relatePeopleTask['task']['tenant_id'];
        }
        unset($departmentIdList[0], $tenantIdList[0], $projectIdList[0]);
        // 项目生产制片查询 组装项目生产制片map
//        $projectMemberList = model(ProjectMemberModel::class)
//            ->where([
//                'project_id' => ['IN', implode(',', $projectIdList)],
//                'role_code' => TaskService::EXECUTIVE_PRODUCER_CODE,
//            ])
//            ->field('project_id,user_id')
//            ->group('project_id,user_id')
//            ->select();
//        $userIdList = array_merge($userIdList, array_column($projectMemberList, 'user_id', 'user_id'));
        unset($userIdList[0]);
        // 根据上面的已有user_id 查询当前系统userMap
        $userList = [];
        if (!empty($userIdList)) {
            $userList = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIdList)]])->field('id,name,union_id')->select();
            $userList = array_column($userList, null, 'id');
        }

        // 根据部门id查询组长 组装部门组长map
//        if (!empty($departmentIdList)) {
//            $filter = [
//                'tenant_id' => ['-in', implode(',', $tenantIdList)],
//                'department_id' => ['-in', implode(',', $departmentIdList)],
//                'role_code' => TaskService::HEADMAN_CODE,
//            ];
//            $userDepartmentMap = UserService::getInstance()->getDepartmentSaasUserMap($filter);
//            foreach ($userDepartmentMap as $departmentUserList) {
//                foreach ($departmentUserList as $departmentUser) {
//                    $userList[$departmentUser['id']] = $departmentUser;
//                }
//            }
//        }
        $unionIdListCc = [];
        foreach ($projectTaskStepCategoryList as $projectId => $taskStepCategoryList) {
            // 抄送给这些环节 配置的【环节制片】
            $unionIdListCcTmp = ProjectService::getInstance()->projectConfigMessageReceiverUnionIdList([
                'project_id' => $projectId,
                'step_category_id' => $taskStepCategoryList,
                'role_code_list' => ['step_producer'],
            ]);
            $unionIdListCc = array_merge($unionIdListCc, $unionIdListCcTmp);
        }
        $unionList = array_column($userList, 'union_id');
        $unionList = array_unique(array_merge($unionList, $unionIdListCc));
        if (empty($unionList)) {
            return;
        }

        unset($relatePeopleTask);
        $taskName = '【' . $entity['initial_episode_code'] . '/' . $entity['showings_number'] . '/' . $entity['name'] . '】';
        if ($enable) {
            $noteText = '废除的任务' . $taskName . '被启用了';
        } else {
            $noteText = '任务' . $taskName . '被废除';
        }
        $templateId = OptionsService::getInstance()->getEntityTaskRemindCommonTemplateId();
        $notifyParam = [
            'first' => '废除任务通知',
            'note_text' => $noteText,
            'remark' => "请及时查看",
            'tenant_id' => $entity['tenant_id'],
            'project_id' => $entity['project_id'],
            'entity_id' => $entity['id'],
            'module_code' => in_array(module_by_id($entity['module_id'])['code'], ['design', 'level', 'asset']) ? 'design' : 'storyboard',
            'message_key' => 'entity_close_operation',
        ];

        $messageContent = [
            "param" => $notifyParam,
            'template_id' => $templateId,
            'content_type' => 'card_message',
            'notice_type' => 'message_demand',
            'is_popup' => 1,
            'message_key' => $notifyParam['message_key'],
        ];
        $messageGenerated = [];
        foreach ($unionList as $receiver) {
            $messageGenerated[] = array_replace($messageContent, [
                'receiver' => $receiver
            ]);
        }


        /***********  发送新的队列  ************/
        foreach ($messageGenerated as $message) {
            Client::send('common_message_pushing', build_queue_data_with_xu([
                'message_generated' => [$message],
            ]));
        }
        /***********  结束  ************/
    }
}
